package com.yx.study.leet.primary.arrary;

import java.util.HashMap;
import java.util.Map;

/**
 * 有效的字母异位词
 * https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn96us/
 * */
public class IsAnagram {


    public boolean isAnagram(String s, String t) {

        if (s.length() != t.length())
            return false;
        Map<Character, Integer> countMap = new HashMap<Character, Integer>();

        for (int i = 0; i < s.length(); i++) {
            if (countMap.get(s.charAt(i)) != null) {
                Integer num = countMap.get(s.charAt(i));
                countMap.put(s.charAt(i), ++num);
            } else {
                countMap.put(s.charAt(i), 1);
            }
        }

        for (int j = 0; j < t.length(); j++) {

            if (countMap.get(t.charAt(j)) == null || countMap.get(t.charAt(j)) == 0) {
                // 不存在字符或字符数量不对
                return false;
            } else {
                Integer num2 = countMap.get(t.charAt(j));
                countMap.put(t.charAt(j), --num2);
            }
        }
        return true;

    }


}
